﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Security.Cryptography;
using System.IO;

namespace EncryptData
{
    public class TripleDES
    {
        byte[] Key = {0xaa, 0xab, 0x5f, 0xc9, 0x12, 0xe2, 0xdc, 0xa4, 0xb1,
          0xc3, 0xa1, 0xfa, 0x17, 0x29, 0x15, 0x9f};
        byte[] IV = {0x1f, 0x0a, 0xb2, 0xbc, 0xf1, 0x8a, 0xeb, 0x7a, 0x59,
          0xe1, 0xf7, 0xa3, 0xd9, 0x42, 0x6f, 0xa2};
        MemoryStream memstrm;
        TripleDESCryptoServiceProvider tdes;
        CryptoStream csw;
        public TripleDES()
        {

        }
        public byte[] EncryptSend(byte[] arraybyte)
        {
            byte[] data = new byte[1];
            Buffer.BlockCopy(arraybyte, 0, data, 0, 1);
            memstrm = new MemoryStream();
            tdes = new TripleDESCryptoServiceProvider();
            csw = new CryptoStream(memstrm, tdes.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
            csw.Write(data, 0, 1);
            csw.FlushFinalBlock();            
            byte[] cryptdata = memstrm.GetBuffer();           
            csw.Close();
            memstrm.Close();
            byte[] result = new byte[arraybyte.Length + 8 - 1];
            Buffer.BlockCopy(cryptdata, 0, result, 0, 8);
            for (int i = 1; i < arraybyte.Length; i++)
            {
                result[i + 7] = arraybyte[i];
            }
            return result;
        }
        public byte[] DecryptReceive(byte[] arraybyte)
        {
            byte[] data = new byte[8];
            Buffer.BlockCopy(arraybyte, 0, data, 0, 8);
            memstrm = new MemoryStream();
            tdes = new TripleDESCryptoServiceProvider();
            byte[] result = new byte[arraybyte.Length - 8 + 1];
            memstrm.Write(data, 0, data.Length);
            memstrm.Position = 0;
            CryptoStream csr = new CryptoStream(memstrm,tdes.CreateDecryptor(Key, IV),CryptoStreamMode.Read);
            csr.Read(result, 0, 1);         
            csr.Close();
            memstrm.Close();
            for (int i = 8; i < arraybyte.Length;i++ )
            {
                result[i - 7] = arraybyte[i];
            }
            return result;
            
        }
       
    }
}
